package com.luoran.bartalks.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.entity.biz.BtContainer;
import com.luoran.bartalks.entity.biz.BtContainerTemplate;
import com.luoran.bartalks.service.IBtCodingRuleService;
import com.luoran.bartalks.service.IBtContainerService;
import com.luoran.bartalks.service.IBtContainerTemplateService;
import com.luoran.bartalks.utils.EnumBillType;
import com.luoran.bartalks.utils.EnumScanType;
import com.luoran.bartalks.utils.UUID;

@Controller
@RequestMapping("/container")
public class BtContainerAction extends AbstractImageAction implements Pageable {
	@Autowired
	private IBtContainerService containerService;

	@Autowired
	private IBtContainerTemplateService templateService;

	@Autowired
	private IBtCodingRuleService codingRuleService;

	@Value("${image.path}")
	private String realpath;

	@Value("${image.url}")
	private String imageUrl;

	private static final Logger log = LoggerFactory.getLogger(BtContainerAction.class);

	/**
	 * 容器管理列表页面
	 * 
	 * @return
	 */
	@RequestMapping
	public String lookContainers(Model model, HttpSession session) {
		log.info("跳转到>>容器管理列表页面");
		List<BtContainerTemplate> btTempalteList = templateService
				.getContainerTemplateByCompanyId(UserContext.get().getCompanyId());
		session.setAttribute("btTempalteList", btTempalteList);
		model.addAttribute("imageUrl", imageUrl);
		return "basics/container-list";
	}

	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) pageQuery.getParas();
		map.put("companyId", UserContext.get().getCompanyId());// 添加查询参数（公司ID）
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("create_time DESC");
		}
		return containerService.getQueryList(pageQuery);
	}

	/**
	 * 生成容器编码
	 */
	@RequestMapping("/productCode")
	@ResponseBody
	public JSONObject generateCoding() {
		return codingRuleService.generateCoding(EnumBillType.CONTAINER, UserContext.get().getCompanyId());
	}

	/**
	 * 调换容器模板时触发事件
	 * 
	 * @return
	 */
	@RequestMapping("findContainerTemplateByTemplateCode")
	@ResponseBody
	public JSONObject findContainerTemplateByTemplateCode(String templateCode) {
		log.info("根据模板编码查询模板信息");
		BtContainerTemplate btTemplateContainer = templateService.getContainerTemplateByCode(templateCode,
				UserContext.get().getCompanyId());
		JSONObject res = new JSONObject();
		if (btTemplateContainer != null) {
			res.put("obj", btTemplateContainer);
			res.put("state", true);
			return res;
		} else {
			res.put("state", false);
			return res;
		}
	}

	/**
	 * 新增容器
	 * 
	 * @param container
	 * @return
	 */
	@RequestMapping("addContainer")
	@ResponseBody
	public JSONObject addContainer(BtContainer container) {
		log.info("新增容器信息>>");
		JSONObject res = new JSONObject();
		res = check(container);
		if (!res.getBooleanValue("state")) {
			return res;
		}
		if (StringUtils.isEmpty(container.getContainerCode())) {
			res.put("msg", "容器编码不能为空");
			res.put("state", false);
			return res;
		}
		// 容器唯一性
		BtContainer persistentContainer = containerService.getContainerByCode(container.getContainerCode(),
				UserContext.get().getCompanyId());
		if (persistentContainer == null) {
			container.setId(UUID.get());
			container.setCreateTime(new Date());
			container.setCompanyId(UserContext.get().getCompanyId());
			container.setStatus(0);
			if (StringUtils.isEmpty(container.getQrcode())) {
				container.setQrcode(EnumScanType.CONTAINER.getValue() + ";" + container.getId());
			} else {
				container.setQrcode(container.getQrcode());
			}
			containerService.addContainer(container);
			res.put("msg", "新增成功");
			res.put("state", true);
			return res;
		} else {
			res.put("msg", "编码“" + container.getContainerCode() + "”已被其他占用");
			res.put("state", false);
			return res;
		}
	}

	/**
	 * 修改保存容器信息
	 * 
	 * @param container
	 * @return
	 */
	@RequestMapping("editContainer")
	@ResponseBody
	public JSONObject editContainer(BtContainer container) {
		log.info("编辑容器信息>>");
		JSONObject res = new JSONObject();
		res = check(container);
		if (!res.getBooleanValue("state")) {
			return res;
		} else {
			BtContainer container1 = containerService.getContainerById(container.getId());
			container.setStatus(0);
			container.setCreateTime(container1.getCreateTime());
			if (StringUtils.isEmpty(container.getQrcode())) {
				container.setQrcode(EnumScanType.CONTAINER.getValue() + ";" + container.getId());
			} else {
				container.setQrcode(container.getQrcode());
			}
			containerService.updateContainer(container);
			res.put("msg", "修改成功");
			res.put("state", true);
			return res;
		}
	}

	/**
	 * 校验输入信息是否合法
	 * 
	 * @param container
	 * @return
	 */
	private JSONObject check(BtContainer container) {
		JSONObject res = new JSONObject();
		List<String> qrcode = containerService.getContainerQrcodeBycompanyId(UserContext.get().getCompanyId());
		if (StringUtils.isEmpty(container.getContainerType())) {
			res.put("msg", "请选择容器类型");
			res.put("state", false);
			return res;
		}
		if (container.getContainerType() == -1) {
			res.put("msg", "请选择容器类型");
			res.put("state", false);
			return res;
		}
		if (StringUtils.isEmpty(container.getLongs())) {
			res.put("msg", "容器长度不能为空");
			res.put("state", false);
			return res;
		}
		if (StringUtils.isEmpty(container.getWide())) {
			res.put("msg", "容器宽度不能为空");
			res.put("state", false);
			return res;
		}
		if (StringUtils.isEmpty(container.getHigh())) {
			res.put("msg", "容器高度不能为空");
			res.put("state", false);
			return res;
		}
		if (StringUtils.isEmpty(container.getBearWeight())) {
			res.put("msg", "承重不能为空");
			res.put("state", false);
			return res;
		}
		if (StringUtils.isEmpty(container.getDeadWeight())) {
			res.put("msg", "自重不能为空");
			res.put("state", false);
			return res;
		}
		if (StringUtils.isEmpty(container.getPermission())) {
			res.put("msg", "容器许可不能为空");
			res.put("state", false);
			return res;
		}
		if (!StringUtils.isEmpty(container.getQrcode())) {
			if (qrcode.contains(container.getQrcode())) {
				BtContainer containerByQrcode = containerService.getContainerByQrcodeAndCompanyId(container.getQrcode(),
						UserContext.get().getCompanyId());
				String id = containerByQrcode.getId();
				if (container.getId() == null) {
					res.put("msg", "新增失败!二维码信息" + container.getQrcode() + "已经存在于编码:"
							+ containerByQrcode.getContainerCode() + "的容器下,请保证同公司下二维码信息的唯一性");
					res.put("state", false);
					return res;
				} else {
					if (!id.equals(container.getId())) {
						res.put("msg", "修改失败!二维码信息" + container.getQrcode() + "已经存在于编码:"
								+ containerByQrcode.getContainerCode() + "的容器下,请保证同公司下二维码信息的唯一性");
						res.put("state", false);
						return res;
					}
				}

			}
		}
		res.put("state", true);
		return res;
	}

	/**
	 * 根据id删除容器信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteContainer/{id}")
	@ResponseBody
	public JSONObject deleteContainer(@PathVariable("id") String id) {
		JSONObject res = new JSONObject();
		BtContainer container = containerService.getContainerById(id);
		container.setStatus(1);
		containerService.updateContainer(container);
		res.put("msg", "删除成功");
		res.put("state", true);
		return res;
	}

	/**
	 * 根据id获取容器信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("getContainer/{id}")
	@ResponseBody
	public JSONObject getContainer(@PathVariable("id") String id) {
		log.info("根据id 获取容器信息>>");
		JSONObject res = new JSONObject();
		BtContainer container = containerService.getContainerById(id);
		res.put("obj", container);
		res.put("state", true);
		res.put("realpath", realpath);
		return res;
	}

	/**
	 * 删除指定的已上传容器图片
	 * 
	 * @param imgUrl
	 * @param id
	 * @return
	 */
	@RequestMapping("delContainerImg")
	@ResponseBody
	public JSONObject delContainerImg(String imgUrl, String id) {
		log.info("删除指定的已上传容器图片>>");
		JSONObject res = new JSONObject();
		BtContainer container = containerService.getContainerById(id);
		String containerUrl = container.getContainerUrl();// 获取容器图片url字段,
		String[] str = containerUrl.split(";");
		List<String> list = new ArrayList<>();
		for (int i = 0; i < str.length; i++) {
			list.add(str[i]);
			File file = new File(realpath + str[i]);
			if (file.exists() && file.isFile()) {
				file.delete();
			}
		}
		list.remove(imgUrl);
		Object[] array = list.toArray();
		containerUrl = org.apache.commons.lang.StringUtils.join(array, ";");
		container.setContainerUrl(containerUrl);
		containerService.updateContainer(container);
		res.put("state", true);
		res.put("containerUrl", containerUrl);
		return res;
	}

	/**
	 * 删除指定的已上传附件图片
	 * 
	 * @param imgUrl
	 * @param id
	 * @return
	 */
	@RequestMapping("delAttachmentImg")
	@ResponseBody
	public JSONObject delAttachmentImg(String imgUrl, String id) {
		log.info("删除指定的已上传附件图片>>");
		JSONObject res = new JSONObject();
		BtContainer container = containerService.getContainerById(id);
		String attachmentUrl = container.getAttachmentUrl();
		String[] str = attachmentUrl.split(";");
		List<String> list = new ArrayList<>();
		for (int i = 0; i < str.length; i++) {
			list.add(str[i]);
			File file = new File(realpath + str[i]);
			if (file.exists() && file.isFile()) {
				file.delete();
			}
		}
		list.remove(imgUrl);
		Object[] array = list.toArray();
		attachmentUrl = org.apache.commons.lang.StringUtils.join(array, ";");
		container.setAttachmentUrl(attachmentUrl);
		containerService.updateContainer(container);
		res.put("state", true);
		res.put("attachmentUrl", attachmentUrl);
		return res;
	}

	// 实现图片上传抽象类,重写getImagePath方法
	@Override
	public String getImagePath(HttpServletRequest request) {
		String strPath = realpath;
		File file = new File(strPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return realpath;
	}

}
